/*
 * @Date: 2023-03-04 21:34:39
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-05 15:13:50
 * @FilePath: \A19\backend\src\api\SourceManage\ApiRenameFolder.ts
 */
/*
 * @Date: 2023-03-04 21:34:39
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-05 10:17:44
 * @FilePath: \A19\backend\src\api\SourceManage\ApiRenameFolder.ts
 */
import { ApiCall } from "tsrpc";
import { ReqRenameFolder, ResRenameFolder } from "../../shared/protocols/SourceManage/PtlRenameFolder";
import { Global } from "../../Global";
import { findFolder } from "../../utils/FindCurrentFolder";

export default async function (call: ApiCall<ReqRenameFolder, ResRenameFolder>) {
    // TODO
    const course = call.req.course
    const root = await Global.collection('folders').findOne({
        course
    })
    if(!root) return call.error('课程不存在')

    const folder = findFolder(call.req.path,root)
    if(!folder) return call.error('文件夹重命名失败')

    const theFolder = folder.folders.find(f => f.name === call.req.name)
    if(!theFolder) return call.error('文件夹重命名失败')
    theFolder.name = call.req.rename

    await Global.collection('folders').updateOne({
        course
    },{
        $set:{
            folders:root.folders
        }
    })

    call.succ({
        files:folder.files,
        folders:folder.folders.map(f => f.name)
    })
}